<template>
	<div class="admini-page">
		<div class="banner">
			<span class="tag">ADMIN</span>
			<h2>这是管理页</h2>
			<p class="desc">欢迎进入后台管理区域</p>
		</div>

		<div class="tips">
			<el-alert
				title="提示"
				type="info"
				description="这是管理页面，仅对具有权限的用户开放。"
				show-icon
				:closable="false"
			/>
		</div>

    <div class="quick-links">
      <el-button type="primary" @click="goRBAC">角色管理</el-button>
    </div>

    <div class="card">
      <div class="card-title">按邮箱搜索用户</div>
      <div class="search-row">
        <el-input
          v-model="email"
          placeholder="请输入邮箱，例如: user@example.com"
          clearable
          @keyup.enter="onSearch"
          class="email-input"
        />
        <el-button type="primary" :loading="loading" :disabled="!email" @click="onSearch">
          搜索
        </el-button>
      </div>

      <div v-if="loading" class="loading-tip">正在查询用户信息...</div>

      <template v-else>
        <UserEditor v-if="user" :user="user" @submit="onSubmitEdit" />

        <el-empty
          v-else-if="searched && !user"
          description="未找到该邮箱对应的用户"
          :image-size="120"
        />
      </template>
    </div>
    </div>
  
</template>

<script setup lang="ts">
// 简单的演示页，无逻辑
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import request from '@/api/request'
import type { User } from '@/types/User'
import { useAdminStore } from '@/stores/admin/admin'
import UserEditor from '@/components/adm/UserEditor.vue'
import { updateUserInfo } from '@/api/auth/user'
const email = ref('')
const router = useRouter()
const loading = ref(false)
const user = ref<User | null>(null)
const searched = ref(false)
const adminStore = useAdminStore()
const emailRe =
  /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/

function formatDate(v?: string | number | Date | null) {
  if (!v) return '—'
  const d = typeof v === 'string' || typeof v === 'number' ? new Date(v) : v
  if (Number.isNaN(+d)) return '—'
  return new Date(d).toLocaleString()
}

function unwrap<T = any>(res: any): T | null {
  if (!res) return null
  if (typeof res === 'object' && 'data' in res) return (res as any).data as T
  return res as T
}

async function onSearch() {
  searched.value = false
  user.value = null

  if (!emailRe.test(email.value.trim())) {
    ElMessage.warning('请输入有效的邮箱地址')
    return
  }

  loading.value = true
  try {
    // console.log('Searching user by email:', email.value)
    const raw = await adminStore.searchUsersByEmail(email.value.trim())
    console.log('Raw search result:', raw)
    let found: any = null
    if (Array.isArray(raw)) {
      found = raw[0] ?? null
    } else if (raw && typeof raw === 'object') {
      const maybeList = (raw as any).list
      if (Array.isArray(maybeList)) {
        found = maybeList[0] ?? null
      } else if ((raw as any).user) {
        found = (raw as any).user
      } else {
        found = raw
      }
    }
    user.value = (found || null) as User | null
  } catch (e: any) {
    const msg =
      e?.raw?.response?.data ||
      e?.message ||
      '查询失败'
    ElMessage.error(typeof msg === 'string' ? msg : '查询失败')
    user.value = null
  } finally {
    searched.value = true
    loading.value = false
  }
}

// 提交编辑后的用户信息
async function onSubmitEdit(payload: Partial<User>) {
  if (!user.value) return
  try {
    const res = await updateUserInfo({ ...payload, id: user.value.id })
    // 兼容 ApiResponse 或直接数据
    const updated = (res as any)?.data ?? (res as any)
    // 更新本地展示数据
    user.value = { ...user.value, ...(updated || payload) } as User
    ElMessage.success('用户信息已保存')
  } catch (e: any) {
    const msg = e?.message || '保存失败'
    ElMessage.error(msg)
  }
}

function goRBAC(){
  router.push('/admin/rbac')
}
</script>

<style scoped>
.admini-page {
	max-width: 960px;
	margin: 0 auto;
	padding: 32px 16px;
}
.banner {
	background: linear-gradient(135deg, #0ea5e9 0%, #3b82f6 100%);
	color: #fff;
	padding: 24px;
	border-radius: 12px;
	box-shadow: 0 8px 20px rgba(59,130,246,0.25);
}
.banner h2 {
	margin: 8px 0 4px;
	font-weight: 700;
}
.banner .desc {
	opacity: 0.9;
}
.tag {
	display: inline-block;
	font-size: 12px;
	letter-spacing: 2px;
	border: 1px solid rgba(255,255,255,0.7);
	padding: 2px 8px;
	border-radius: 999px;
}
.tips { margin-top: 16px; }

.quick-links { margin-top:16px; }

/* 新增样式 */
.card {
  margin-top: 16px;
  background: #fff;
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.06);
}
.card-title {
  font-weight: 600;
  margin-bottom: 12px;
}
.search-row {
  display: flex;
  gap: 12px;
  align-items: center;
}
.email-input {
  flex: 1;
}
.loading-tip {
  margin-top: 12px;
  color: #666;
}
.result-card {
  margin-top: 16px;
}
.result-grid {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 8px 16px;
}
.item .label {
  color: #666;
}
@media (max-width: 640px) {
  .result-grid {
    grid-template-columns: 1fr;
  }
}
</style>
